<template>
  <div class="flex h-full flex-col p-4">
    <!-- 搜索表单 -->
    <Card :bordered="false" class="mb-4 flex-shrink-0">
      <Space wrap>
        <Input
          v-model:value="searchParams.permissionCode"
          placeholder="权限编码"
          allow-clear
          style="width: 200px"
          @press-enter="handleSearch"
        />
        <Input
          v-model:value="searchParams.permissionName"
          placeholder="权限名称"
          allow-clear
          style="width: 200px"
          @press-enter="handleSearch"
        />
        <Select
          v-model:value="searchParams.permissionType"
          placeholder="权限类型"
          allow-clear
          style="width: 150px"
        >
          <SelectOption :value="PermissionType.URL">接口权限</SelectOption>
          <SelectOption :value="PermissionType.BUTTON">按钮权限</SelectOption>
        </Select>
        <TreeSelect
          v-model:value="searchParams.menuId"
          placeholder="所属菜单"
          allow-clear
          tree-default-expand-all
          style="width: 200px"
          :tree-data="menuTreeData"
          :field-names="{ label: 'menuName', value: 'id', children: 'children' }"
        />
        <Button type="primary" @click="handleSearch">
          <template #icon><SearchOutlined /></template>
          查询
        </Button>
        <Button @click="handleReset">
          <template #icon><ReloadOutlined /></template>
          重置
        </Button>
      </Space>
    </Card>

    <!-- 表格 -->
    <Card :bordered="false" class="flex flex-1 flex-col overflow-hidden">
      <div class="mb-4 flex flex-shrink-0 justify-between">
        <Space>
          <Button v-permission="'sys:permission:add'" type="primary" @click="handleAdd">
            <template #icon><PlusOutlined /></template>
            新增权限
          </Button>
        </Space>
      </div>

      <div class="flex-1 overflow-hidden">
        <Grid class="h-full" @page-change="handlePageChange">
          <!-- 权限类型 -->
          <template #permissionType="{ row }">
            <Tag :color="row.permissionType === PermissionType.URL ? 'blue' : 'green'">
              {{ row.permissionType === PermissionType.URL ? '接口权限' : '按钮权限' }}
            </Tag>
          </template>

          <!-- 请求方法 -->
          <template #method="{ row }">
            <Tag v-if="row.method" :color="getMethodColor(row.method)">
              {{ row.method }}
            </Tag>
            <span v-else>-</span>
          </template>

          <!-- 所属菜单 -->
          <template #menuName="{ row }">
            <span v-if="row.menuName">{{ row.menuName }}</span>
            <span v-else-if="row.menuId">
              <Tag color="orange">ID: {{ row.menuId }}</Tag>
              <span style="color: #999; font-size: 12px;">（菜单不存在）</span>
            </span>
            <span v-else>-</span>
          </template>

          <!-- 操作 -->
          <template #action="{ row }">
            <Space>
              <Button
                v-permission="'sys:permission:edit'"
                type="link"
                size="small"
                @click="handleEdit(row)"
              >
                <template #icon><EditOutlined /></template>
                编辑
              </Button>
              <Button
                v-permission="'sys:permission:delete'"
                type="link"
                size="small"
                danger
                @click="handleDelete(row)"
              >
                <template #icon><DeleteOutlined /></template>
                删除
              </Button>
            </Space>
          </template>
        </Grid>
      </div>
    </Card>

    <!-- 新增/编辑弹窗 -->
    <PermissionFormModal
      v-model:visible="modalVisible"
      :permission="currentPermission"
      :menu-tree="menuTreeData"
      @success="handleModalSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';

import { useVbenVxeGrid } from '@vben/plugins/vxe-table';

import {
  Button,
  Card,
  Input,
  message,
  Modal,
  Select,
  SelectOption,
  Space,
  Tag,
  TreeSelect,
} from 'ant-design-vue';
import {
  DeleteOutlined,
  EditOutlined,
  PlusOutlined,
  ReloadOutlined,
  SearchOutlined,
} from '@ant-design/icons-vue';

import type { RoleMenuTreeNode } from '#/api/core/role';
import { getRoleMenuTree } from '#/api/core/role';
import type { Permission, PermissionQueryParams } from '#/api/core/permission';
import {
  batchDeletePermissionApi,
  deletePermissionApi,
  getPermissionListApi,
  PermissionType,
} from '#/api/core/permission';

import PermissionFormModal from './permission-form-modal.vue';

// 搜索参数
const searchParams = reactive<PermissionQueryParams>({
  permissionCode: undefined,
  permissionName: undefined,
  permissionType: undefined,
  menuId: undefined,
  pageNum: 1,
  pageSize: 10,
});

// 菜单树数据（使用角色菜单树结构，包含 checked 字段）
const menuTreeData = ref<RoleMenuTreeNode[]>([]);

// 弹窗
const modalVisible = ref(false);
const currentPermission = ref<Permission | undefined>();

// 使用 vxe-table
const [Grid, gridApi] = useVbenVxeGrid<Permission>({
  gridOptions: {
    data: [],
    loading: false,
    pagerConfig: {
      enabled: true,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      pageSizes: [10, 20, 50, 100],
      layouts: [
        'PrevJump',
        'PrevPage',
        'Number',
        'NextPage',
        'NextJump',
        'Sizes',
        'Total',
      ],
    },
    columns: [
      {
        field: 'permissionCode',
        title: '权限编码',
        minWidth: 180,
      },
      {
        field: 'permissionName',
        title: '权限名称',
        minWidth: 150,
      },
      {
        field: 'permissionType',
        title: '权限类型',
        width: 120,
        align: 'center',
        slots: { default: 'permissionType' },
      },
      {
        field: 'url',
        title: '接口地址',
        minWidth: 200,
      },
      {
        field: 'method',
        title: '请求方法',
        width: 100,
        align: 'center',
        slots: { default: 'method' },
      },
      {
        field: 'menuName',
        title: '所属菜单',
        width: 150,
        slots: { default: 'menuName' },
      },
      {
        field: 'action',
        title: '操作',
        width: 180,
        align: 'center',
        fixed: 'right',
        slots: { default: 'action' },
      },
    ],
  },
});

// 提取所有菜单ID（包括子节点）
function extractAllMenuIds(menus: RoleMenuTreeNode[]): number[] {
  const ids: number[] = [];
  function traverse(nodes: RoleMenuTreeNode[]) {
    for (const node of nodes) {
      ids.push(node.id);
      if (node.children && node.children.length > 0) {
        traverse(node.children);
      }
    }
  }
  traverse(menus);
  return ids;
}

// 加载菜单树（使用角色菜单树 API，不传 roleId 获取所有菜单）
async function loadMenuTree() {
  try {
    // 不传 roleId，获取所有菜单（包括目录、菜单、按钮）
    const data = await getRoleMenuTree();
    menuTreeData.value = data;

    const allIds = extractAllMenuIds(data);
    console.log('📋 加载菜单树成功:', {
      菜单树数量: menuTreeData.value.length,
      所有菜单ID: allIds,
      菜单树: menuTreeData.value,
    });

    // 检查菜单树中是否包含 permissionCode 字段
    if (data.length > 0) {
      console.log('🔍 检查第一个菜单节点:', data[0]);
      console.log('🔍 是否包含 permissionCode:', 'permissionCode' in data[0]);
    }
  } catch (error: any) {
    message.error(error?.msg || '加载菜单树失败');
  }
}

// 从菜单树中查找菜单名称
function findMenuNameById(menuId?: number): string {
  if (!menuId) return '';

  function traverse(menus: RoleMenuTreeNode[]): string {
    for (const menu of menus) {
      if (menu.id === menuId) {
        return menu.menuName;
      }
      if (menu.children && menu.children.length > 0) {
        const found = traverse(menu.children);
        if (found) return found;
      }
    }
    return '';
  }

  return traverse(menuTreeData.value);
}

// 加载权限列表
async function loadPermissionList() {
  gridApi.setState({ gridOptions: { loading: true } });
  try {
    const data = await getPermissionListApi(searchParams);

    // 处理不同的分页格式
    let list: Permission[] = [];
    let total = 0;
    let currentPage = 1;

    if (data.list) {
      list = data.list;
      total = data.total;
      currentPage = data.pageNum || searchParams.pageNum || 1;
    } else if (data.records) {
      list = data.records;
      total = data.total;
      currentPage = data.current || searchParams.pageNum || 1;
    }

    // 如果后端没有返回 menuName，从菜单树中查找
    const processedList = list.map((item) => {
      if (!item.menuName && item.menuId) {
        return {
          ...item,
          menuName: findMenuNameById(item.menuId),
        };
      }
      return item;
    });

    gridApi.setState({
      gridOptions: {
        data: processedList,
        loading: false,
        pagerConfig: {
          total: total,
          currentPage: currentPage,
          pageSize: searchParams.pageSize || 10,
        },
      },
    });

    console.log('📋 权限列表加载完成:', {
      数量: processedList.length,
      示例: processedList.slice(0, 3),
    });
  } catch (error: any) {
    message.error(error?.msg || '加载权限列表失败');
    gridApi.setState({ gridOptions: { loading: false } });
  }
}

// 搜索
function handleSearch() {
  searchParams.pageNum = 1;
  loadPermissionList();
}

// 重置
function handleReset() {
  searchParams.permissionCode = undefined;
  searchParams.permissionName = undefined;
  searchParams.permissionType = undefined;
  searchParams.menuId = undefined;
  searchParams.pageNum = 1;
  searchParams.pageSize = 10;
  loadPermissionList();
}

// 分页变化
function handlePageChange({ currentPage, pageSize }: any) {
  searchParams.pageNum = currentPage;
  searchParams.pageSize = pageSize;
  loadPermissionList();
}

// 新增
function handleAdd() {
  currentPermission.value = undefined;
  modalVisible.value = true;
}

// 编辑
function handleEdit(record: Permission) {
  currentPermission.value = { ...record };
  console.log('🔧 编辑权限 - 主页面:', {
    '权限记录': record,
    '菜单ID': record.menuId,
    '菜单ID类型': typeof record.menuId,
    '菜单名称': record.menuName,
    '菜单树数量': menuTreeData.value.length,
    '菜单树': menuTreeData.value,
  });
  modalVisible.value = true;
}

// 删除
function handleDelete(record: Permission) {
  Modal.confirm({
    title: '确认删除',
    content: `确定要删除权限"${record.permissionName}"吗？`,
    onOk: async () => {
      try {
        await deletePermissionApi(record.id!);
        message.success('删除成功');
        loadPermissionList();
      } catch (error: any) {
        message.error(error?.msg || '删除失败');
      }
    },
  });
}

// 批量删除
function handleBatchDelete() {
  // 这里暂时不实现批量删除，因为需要获取选中的记录
  // 如果需要批量删除功能，需要添加 checkbox 列和相关逻辑
  message.warning('批量删除功能暂未实现');
}

// 弹窗成功回调
function handleModalSuccess() {
  loadPermissionList();
}

// 获取请求方法颜色
function getMethodColor(method: string): string {
  const colorMap: Record<string, string> = {
    GET: 'blue',
    POST: 'green',
    PUT: 'orange',
    DELETE: 'red',
    PATCH: 'purple',
  };
  return colorMap[method.toUpperCase()] || 'default';
}

// 初始化
onMounted(() => {
  loadMenuTree();
  loadPermissionList();
});
</script>



